﻿// This code is released under the BSD license.
namespace PugLib
{
    using System;
    using System.Linq.Expressions;

    public class ValidatedObject<T>
    {
        private readonly Func<T, bool> _expression;
        private T _value;

        public ValidatedObject(T value, Func<T, bool> validator)
        {
            _value = value;
            _expression = validator;
        }

        public ValidatedObject(T value, Expression<Func<T, bool>> expression)
        {
            _value = value;
            _expression = expression.Compile();
        }

        public T Value
        {
            get
            {
                if (IsValid)
                {
                    return _value;
                }
                throw new InvalidOperationException("Invalid value in ValidatedObject");
            }
            set
            {
                _value = value;
                if (!IsValid)
                {
                    throw new InvalidOperationException("Invalid value in ValidatedObject");
                }
            }
        }

        private bool IsValid
        {
            get { return _expression(_value); }
        }
    }
}